package com.neusoft.nepa.controller;

import com.neusoft.nepa.UserLogin;
import com.neusoft.nepa.entity.Admin;
import com.neusoft.nepa.entity.AdminData;
import com.neusoft.nepa.entity.AdminDataDTO;
import com.neusoft.nepa.entity.ProvinceProblem;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import static com.neusoft.nepb.common.FileUtils.readMapObject;
import static com.neusoft.nepb.common.FileUtils.writeMapObject;

public class SeclectNetViewController1 {
    private HashMap<String, String[]> userMap = new HashMap<>();
    @FXML
    private Label titleLabel;
    private AdminData data;
    @FXML
    private TextArea outputText;
    @FXML
    private TextField inputName;
    @FXML
    private Label ifDiffRegion;

    public void initialize() {
        Platform.runLater(() -> {
            try {
                getMap();
            } catch (FileNotFoundException e) {
                showAlert("数据加载失败", "错误", e.getMessage());
            }
        });
    }

    @FXML
    private void back(ActionEvent event) throws IOException {
        Stage stage = (Stage) titleLabel.getScene().getWindow();
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/neusoft/nepa/view/PublicSuperviseDetail.fxml"));
        Parent root = fxmlLoader.load();
        Scene newScene = new Scene(root, 960, 540);
        stage.setScene(newScene);
        stage.setResizable(false);
        stage.setTitle("Register");
        stage.show();
    }

    private void getMap() throws FileNotFoundException {
        userMap = UserLogin.deptAccountToNepc();
        Stage stage = (Stage) titleLabel.getScene().getWindow();
        data = (AdminData) stage.getProperties().get("userInformation");
    }

    @FXML
    private void checkUser() {
        String input = inputName.getText().trim();
        if (input.equals("/listall") || input.equals("/Listall") || input.equals("/listAll")) {
            StringBuilder sb = new StringBuilder();
            for (String[] str : userMap.values()) {
                sb.append("网格员 : ").append(str[2]).append("\n").append("地区为 : ").append(str[1]).append("\n");
            }
            outputText.setText(sb.toString());
        } else {
            if (!input.isEmpty() && userMap.containsKey(input)) {
                String[] tempString = userMap.get(input);
                StringBuilder sb = new StringBuilder();
                sb.append("已找到网格员 : ").append(tempString[2]).append("\n");
                sb.append("网格员地区 : ").append(tempString[1]).append("\n");
                sb.append("已获得的信息：\n" +
                        "由 ").append(data.getFeedbackName()).append(" 返回信息\n" +
                        "日期：").append(data.getFeedbackDate()).append(" \n" +
                        "时间: ").append(data.getFeedbackTime()).append("\n" +
                        "等级：").append(data.getPreviewIndex()).append("\n描述：").append(data.getInfo());
                outputText.setText(sb.toString());
                if (!tempString[1].startsWith(data.getWithinProvince())) {
                    ifDiffRegion.setText("此指派为异地指派，请注意");
                } else {
                    ifDiffRegion.setText(" ");
                }
            } else {
                StringBuilder sb = new StringBuilder();
                sb.append("未找到网格员").append("\n");
                sb.append("已获得的信息：\n" +
                        "由 ").append(data.getFeedbackName()).append(" 返回信息 \n" +
                        "日期：").append(data.getFeedbackDate()).append(" \n" +
                        "时间: ").append(data.getFeedbackTime()).append("\n" +
                        "等级：").append(data.getPreviewIndex()).append("\n描述：").append(data.getInfo());
                outputText.setText(sb.toString());
                ifDiffRegion.setText("");
            }
        }
    }

    @FXML
    private void submit(ActionEvent event) throws IOException {
        // 1. 校验 inputName 非空
        String input = inputName.getText().trim();
        if (input.isEmpty()) {
            showAlert("输入不能为空", "错误", "请输入网格员标识");
            return;
        }

        // 2. 安全读取 Arrange 对象
        HashMap<String, ArrayList<AdminDataDTO>> Arrange;
        try {
            Arrange = (HashMap<String, ArrayList<AdminDataDTO>>) readMapObject("src/com/neusoft/nepa/arrange_list.txt");
            // 若文件不存在或读取失败，Arrange 设为空 HashMap
            if (Arrange == null) {
                Arrange = new HashMap<>();
            }
        } catch (Exception e) {
            showAlert("数据读取失败", "错误", "读取安排列表失败：" + e.getMessage());
            return;
        }

        // 3. 处理数据添加
        AdminDataDTO dto = new AdminDataDTO(data);
        System.out.println(dto.getWithinProvince());

        // 安全获取列表（防御性编程）
        ArrayList<AdminDataDTO> list = Arrange.get(input);
        if (list == null) {
            list = new ArrayList<>();
            Arrange.put(input, list);
        }
        list.add(dto); // 现在可安全添加

        // 4. 写入文件
        try {
            writeMapObject("src/com/neusoft/nepa/arrange_list.txt", Arrange);
        } catch (Exception e) {
            showAlert("数据保存失败", "错误", "保存安排列表失败：" + e.getMessage());
            return;
        }

        // 5. 提示并跳转
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Submitted");
        alert.setContentText("已提交");
        alert.showAndWait();

        Stage stage = (Stage) outputText.getScene().getWindow();
        stage.close();
    }

    private void showAlert(String title, String header, String content) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(content);
        alert.showAndWait();
    }
}